package linter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import linter.POJO.DO.UserCard;
import linter.POJO.DTO.UserCardDTO;
import linter.mapper.UserCardMapper;
import linter.service.UserCardService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;

import static linter.custom.Constant.*;
import static linter.custom.CustomResultType.*;
import static linter.custom.CustomResultType.UPLOAD_ERROR;
import static linter.utils.ModelUtils.generateUUID;

/**
* @author 北煜
* @description 针对表【user_card(用户卡片详情表)】的数据库操作Service实现
* @createDate 2023-07-10 15:57:39
*/
@Service
public class UserCardServiceImpl extends ServiceImpl<UserCardMapper, UserCard>
    implements UserCardService{
    @Resource
    UserCardMapper userCardMapper;

    @Override
    public String getImgHeadById(Long id) {
        return userCardMapper.getImgHeadById(id);
    }
    @Override
    public String getUserNameById(Long id) {
        return userCardMapper.getUserNameById(id);
    }

    @Override
    public String updateUserCard(UserCardDTO userCardDTO, Long uuid, MultipartFile file) {
        Date date = new Date();
        UserCard userCard = new UserCard();
        QueryWrapper<UserCard> queryWrapper = new QueryWrapper<>();

        if (!file.isEmpty()){
            //构造一个带指定Region对象的配置类
            Configuration cfg = new Configuration(Region.region2());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(ACCESS_KEY_QINIU, SECRET_KEY_QINIU);
            String bucketName = BUCKET_NAME_QINIU;
            String key = "User/images/" + userCardDTO.getId() + "/" + generateUUID() + userCardDTO.getNickname();
            // 保存在数据库中，到时候进行拼接
            String baseUrl = "http://qiniuyun.linter.top";
            String url = baseUrl + "/" + key;
            byte[] fileContent = new byte[0];
            try {
                fileContent = file.getBytes();
                try(ByteArrayInputStream inputStream = new ByteArrayInputStream(fileContent)){
                    String upToken = auth.uploadToken(bucketName);
                    Response response = uploadManager.put(inputStream, key, upToken, null, null);
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

                    userCard.setImgUrlIcon(url);
                    userCard.setNickname(userCardDTO.getNickname());
                    userCard.setSex(userCardDTO.getSex());
                    userCard.setBirthday(userCardDTO.getBirthday());
                    userCard.setSignature(userCardDTO.getSignature());
                    userCard.setUpdateTime(date);
                    int flag = userCardMapper.update(userCard, queryWrapper
                            .eq("id", uuid).eq("is_delete", 0));
                    if (response.statusCode == RES_SUCCESS) {
                        return  flag != 1 ? UPDATE_ERROR + "and" + UPLOAD_ERROR
                                : UPDATE_SUCCESS+putRet.hash + ": " + UPLOAD_SUCCESS;
                    } else {
                        throw new RuntimeException(UPLOAD_ERROR + ": " + response.bodyString());
                    }
                }catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        userCard.setImgUrlIcon(DEFAULT_IMG_URL_ICON);
        userCard.setNickname(userCardDTO.getNickname());
        userCard.setSex(userCardDTO.getSex());
        userCard.setBirthday(userCardDTO.getBirthday());
        userCard.setSignature(userCardDTO.getSignature());
        userCard.setUpdateTime(date);
        int flag = userCardMapper.update(userCard, queryWrapper
                .eq("id", uuid).eq("is_delete", 0));
        return  flag != 1 ? UPDATE_ERROR : UPDATE_SUCCESS;
    }

    @Override
    public UserCard getUserCardById(Long uuid) {
        return userCardMapper.selectById(uuid);
    }
}




